package com.swipemaster.game;

import android.annotation.SuppressLint;
import android.graphics.Canvas;
import android.view.SurfaceHolder;

import com.swipemaster.common.Const;
import com.swipemaster.common.Global;

public class GameThread extends Thread
{
	private final SurfaceHolder surfaceHolder = Global.app.gameSurface.getHolder();
	private boolean isRunning;

	public boolean isRunning()
	{
		return isRunning;
	}

	@SuppressLint("WrongCall")
	@Override
	public void run()
	{
		Canvas canvas = null;
		while (isRunning)
		{
			try
			{
				canvas = surfaceHolder.lockCanvas();
				Global.app.gameSurface.onDraw(canvas);
				Global.app.gameSurface.updateGame();
			}
			finally
			{
				// Do this in a finally so that if an exception is thrown during the above,
				// we don't leave the Surface in an inconsistent state.
				if (canvas != null)
				{
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}
			// Painting thread is going to sleep for a while. It allows CPU faster events handling,
			// because it's less overwhelmed.
			try
			{
				Thread.sleep(Const.MS_BETWEEN_PAINT);
			}
			catch (final InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}

	public void setRunning(boolean isRunning)
	{
		this.isRunning = isRunning;
	}
}